<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en">
<!--<![endif]-->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Transactions - The .NET Core ORM Cookbook</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link rel="stylesheet" href="css/theme.css" type="text/css" />
    <link rel="stylesheet" href="css/theme_colors.css" type="text/css" />
    <link rel="stylesheet" href="css/styles/vs.css">
    <link rel="stylesheet" href="css/font-awesome.4.5.0.min.css">
</head>
<body role="document">
    <div class="grid-for-nav">
        <nav data-toggle="nav-shift" class="nav-side stickynav">
            <div class="side-nav-search">
                <a href="index.htm"><i class="fa fa-home"></i> The .NET Core ORM Cookbook</a>
                <div role="search">
                    <form id="search-form" class="form" action="Docnet_search.htm" method="get">
                        <input type="text" name="q" placeholder="Search docs" />
                    </form>
                </div>
            </div>
            <div class="menu menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul>
<li class="tocentry"><a href="index.htm">Home</a>
</li>

<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="ORMs.htm">ORMs</a></span>
</li>
<li class="tocentry"><a href="FAQ.htm">FAQ</a>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="StandardCRUDscenarios.htm">Standard CRUD scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Fetchingdatascenarios.htm">Fetching data scenarios</a></span>
</li>
<li class="tocentry">
<ul>
<li><span class="navigationgroup"><i class="fa fa-caret-down"></i> <a href="Advancedscenarios.htm">Advanced scenarios</a></span></li>
<li class="tocentry"><a href="SingleModelCrudAsync.htm">Async Operations</a>
</li>
<li class="tocentry"><a href="LargeBatch.htm">Batch Inserts with Large Collections</a>
</li>
<li class="tocentry"><a href="BulkInsert.htm">Bulk Inserts</a>
</li>
<li class="tocentry"><a href="ConnectionSharing.htm">Connection Sharing</a>
</li>
<li class="tocentry"><a href="MultipleDB.htm">Multiple Databases</a>
</li>
<li class="tocentry"><a href="PartialUpdate.htm">Partial Updates</a>
</li>
<li class="tocentry current"><a class="current" href="Transactions.htm">Transactions</a>
<ul class="currentrelative">
<li class="tocentry"><a href="#scenario-prototype">Scenario Prototype</a></li>

<li class="tocentry"><a href="#ado.net">ADO.NET</a></li>

<li class="tocentry"><a href="#chain">Chain</a></li>

<li class="tocentry"><a href="#dapper">Dapper</a></li>

<li class="tocentry"><a href="#dbconnector">DbConnector</a></li>

<li class="tocentry"><a href="#entity-framework-6">Entity Framework 6</a></li>

<li class="tocentry"><a href="#entity-framework-core">Entity Framework Core</a></li>

<li class="tocentry"><a href="#linq-to-db">LINQ to DB</a></li>

<li class="tocentry"><a href="#llblgen-pro">LLBLGen Pro</a></li>

<li class="tocentry"><a href="#nhibernate">NHibernate</a></li>

<li class="tocentry"><a href="#repodb">RepoDb</a></li>

<li class="tocentry"><a href="#servicestack">ServiceStack</a></li>



</ul>
<li class="tocentry"><a href="Upsert.htm">Upsert</a>
</li>

</ul>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Sortingscenarios.htm">Sorting scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Storedprocedurescenarios.htm">Stored procedure scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Auditingandhistoryscenarios.htm">Auditing and history scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="Multi-Tenancyscenarios.htm">Multi-Tenancy scenarios</a></span>
</li>
<li class="tocentry">
<span class="navigationgroup"><i class="fa fa-caret-right"></i> <a href="UnknownDatabasescenarios.htm">Unknown Database scenarios</a></span>
</li>
</ul>
				<div class="toc-footer">
					<span class="text-small">
						<hr/>
						<a href="https://github.com/FransBouma/DocNet" target="_blank">Made with <i class="fa fa-github"></i> DocNet</a>
					</span>
				</div>	
			</div>
            &nbsp;
        </nav>
        <section data-toggle="nav-shift" class="nav-content-wrap">
            <nav class="nav-top" role="navigation" aria-label="top navigation">
                <i data-toggle="nav-top" class="fa fa-bars"></i>
                <a href="index.htm">The .NET Core ORM Cookbook</a>
            </nav>
            <div class="nav-content">
                <div role="navigation" aria-label="breadcrumbs navigation">
                    <div class="breadcrumbs">
<ul><li><a href="index.htm">Home</a></li> / <li><a href="Advancedscenarios.htm">Advanced scenarios</a></li> / <li><a href="Transactions.htm">Transactions</a></li></ul>
					
                    </div>
                    <hr />
                </div>
                <div role="main">
                    <div class="section">
<h1 id="working-with-transactions">Working with Transactions<a class="headerlink" href="#working-with-transactions" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h1>
<p>These scenarios demonstrate how to create a transaction and then commit or rollback. </p>
<h2 id="scenario-prototype">Scenario Prototype<a class="headerlink" href="#scenario-prototype" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">public interface ITransactionsScenario&lt;TEmployeeClassification&gt;
   where TEmployeeClassification : class, IEmployeeClassification, new()
{
    /// &lt;summary&gt;
    /// Create a new EmployeeClassification row, returning the new primary key.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;classification&quot;&gt;The classification.&lt;/param&gt;
    /// &lt;param name=&quot;shouldRollBack&quot;&gt;If True, the pending transaction should be rolled back.&lt;/param&gt;
    /// &lt;param name=&quot;isolationLevel&quot;&gt;The isolation level.&lt;/param&gt;
    /// &lt;returns&gt;System.Int32.&lt;/returns&gt;
    int Create(TEmployeeClassification classification, bool shouldRollBack);

    /// &lt;summary&gt;
    /// Create a new EmployeeClassification row, returning the new primary key.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;classification&quot;&gt;The classification.&lt;/param&gt;
    /// &lt;param name=&quot;shouldRollBack&quot;&gt;If True, the pending transaction should be rolled back.&lt;/param&gt;
    /// &lt;param name=&quot;isolationLevel&quot;&gt;The isolation level.&lt;/param&gt;
    /// &lt;returns&gt;System.Int32.&lt;/returns&gt;
    int CreateWithIsolationLevel(TEmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel);

    /// &lt;summary&gt;
    /// Gets an EmployeeClassification row by its primary key. If no row is found, a null is returned.
    /// &lt;/summary&gt;
    TEmployeeClassification? GetByKey(int employeeClassificationKey);
}
</code></pre>

<h2 id="ado.net">ADO.NET<a class="headerlink" href="#ado.net" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>While there is an open transaction against a connection, all commands must be explcitly provided with the transaction object. </p>
<pre><code class="cs">public class TransactionsScenario : SqlServerScenarioBase, ITransactionsScenario&lt;EmployeeClassification&gt;
{
    public TransactionsScenario(string connectionString) : base(connectionString)
    { }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        const string sql = @&quot;INSERT INTO HR.EmployeeClassification (EmployeeClassificationName)
                    OUTPUT Inserted.EmployeeClassificationKey
                    VALUES(@EmployeeClassificationName )&quot;;

        using (var con = OpenConnection())
        using (var trans = con.BeginTransaction())
        using (var cmd = new SqlCommand(sql, con, trans))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationName&quot;, classification.EmployeeClassificationName);
            var result = (int)cmd.ExecuteScalar();

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        const string sql = @&quot;INSERT INTO HR.EmployeeClassification (EmployeeClassificationName)
                    OUTPUT Inserted.EmployeeClassificationKey
                    VALUES(@EmployeeClassificationName )&quot;;

        using (var con = OpenConnection())
        using (var trans = con.BeginTransaction(isolationLevel))
        using (var cmd = new SqlCommand(sql, con, trans))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationName&quot;, classification.EmployeeClassificationName);
            var result = (int)cmd.ExecuteScalar();

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        const string sql = @&quot;SELECT ec.EmployeeClassificationKey, ec.EmployeeClassificationName
                    FROM HR.EmployeeClassification ec
                    WHERE ec.EmployeeClassificationKey = @EmployeeClassificationKey;&quot;;

        using (var con = OpenConnection())
        using (var cmd = new SqlCommand(sql, con))
        {
            cmd.Parameters.AddWithValue(&quot;@EmployeeClassificationKey&quot;, employeeClassificationKey);
            using (var reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                    return null;

                return new EmployeeClassification()
                {
                    EmployeeClassificationKey = reader.GetInt32(reader.GetOrdinal(&quot;EmployeeClassificationKey&quot;)),
                    EmployeeClassificationName = reader.GetString(reader.GetOrdinal(&quot;EmployeeClassificationName&quot;))
                };
            }
        }
    }
}
</code></pre>

<h2 id="chain">Chain<a class="headerlink" href="#chain" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>When calling <code>DataSource.BeginTransaction()</code>, you get a <code>TransactionalDataSource</code> with the capabilities of the original <code>DataSource</code>. </p>
<p>Unlike a normal <code>DataSource</code>, a <code>TransactionalDataSource</code> holds an open database connection and thus must be disposed after use.</p>
<pre><code class="cs">public class TransactionsScenario : ITransactionsScenario&lt;EmployeeClassification&gt;
{
    readonly SqlServerDataSource m_DataSource;

    public TransactionsScenario(SqlServerDataSource dataSource)
    {
        m_DataSource = dataSource;
    }

    public int Create(EmployeeClassification classification)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        return m_DataSource.Insert(classification).ToInt32().Execute();
    }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        using (var trans = m_DataSource.BeginTransaction())
        {
            var result = trans.Insert(classification).ToInt32().Execute();

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        using (var trans = m_DataSource.BeginTransaction(isolationLevel: isolationLevel))
        {
            var result = trans.Insert(classification).ToInt32().Execute();

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        return m_DataSource.GetByKey&lt;EmployeeClassification&gt;(employeeClassificationKey).ToObjectOrNull().Execute();
    }
}
</code></pre>

<h2 id="dapper">Dapper<a class="headerlink" href="#dapper" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>While there is an open transaction against a connection, all commands must be explcitly provided with the transaction object. </p>
<pre><code class="cs">public class TransactionsScenario : ScenarioBase, ITransactionsScenario&lt;EmployeeClassification&gt;
{
    public TransactionsScenario(string connectionString) : base(connectionString)
    {
    }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;INSERT INTO HR.EmployeeClassification (EmployeeClassificationName)
                    OUTPUT Inserted.EmployeeClassificationKey
                    VALUES(@EmployeeClassificationName )&quot;;

        using (var con = OpenConnection())
        using (var trans = con.BeginTransaction())
        {
            var result = con.ExecuteScalar&lt;int&gt;(sql, classification, transaction: trans);

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;INSERT INTO HR.EmployeeClassification (EmployeeClassificationName)
                    OUTPUT Inserted.EmployeeClassificationKey
                    VALUES(@EmployeeClassificationName )&quot;;

        using (var con = OpenConnection())
        using (var trans = con.BeginTransaction(isolationLevel))
        {
            var result = con.ExecuteScalar&lt;int&gt;(sql, classification, transaction: trans);

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        using (var con = OpenConnection())
            return con.Get&lt;EmployeeClassification&gt;(employeeClassificationKey);
    }
}
</code></pre>

<h2 id="dbconnector">DbConnector<a class="headerlink" href="#dbconnector" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>DbConnector will automatically create transactions for all <code>Non-Query</code> executions or when invoking <code>WithIsolationLevel</code> and setting a proper isolation level.</p>
<p>Otherwise, a custom transaction can be used and configured via the <code>Execute</code> functions.</p>
<pre><code class="cs">public class TransactionsScenario : ScenarioBase, ITransactionsScenario&lt;EmployeeClassification&gt;
{
    public TransactionsScenario(string connectionString) : base(connectionString)
    {
    }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;INSERT INTO HR.EmployeeClassification (EmployeeClassificationName)
                    OUTPUT Inserted.EmployeeClassificationKey
                    VALUES(@EmployeeClassificationName )&quot;;

        using (var con = OpenConnection())
        using (var trans = con.BeginTransaction())
        {
            //Set the custom transaction when invoking Execute
            var result = DbConnector.Scalar&lt;int&gt;(sql, classification).Execute(trans);

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        var sql = @&quot;INSERT INTO HR.EmployeeClassification (EmployeeClassificationName)
                    OUTPUT Inserted.EmployeeClassificationKey
                    VALUES(@EmployeeClassificationName )&quot;;

        using (var con = OpenConnection())
        using (var trans = con.BeginTransaction(isolationLevel))
        {
            //Set the custom transaction when invoking Execute
            var result = DbConnector.Scalar&lt;int&gt;(sql, classification).Execute(trans);

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        string sql = &quot;SELECT * FROM &quot; + EmployeeClassification.TableName + &quot; WHERE EmployeeClassificationKey = @employeeClassificationKey;&quot;;

        return DbConnector.ReadFirstOrDefault&lt;EmployeeClassification&gt;(sql, new { employeeClassificationKey })
                           .WithIsolationLevel(IsolationLevel.ReadCommitted) //Enable the use of a transaction
                           .Execute();
    }
}
</code></pre>

<h2 id="entity-framework-6">Entity Framework 6<a class="headerlink" href="#entity-framework-6" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>Entity Framework will automatically create and commit a transaction when you call <code>SaveChanges()</code>. To override this behavior, you can explicitly create a transaction. </p>
<p>When setting the isolation level, you need to use an extension method defined in <code>Microsoft.EntityFramework.RelationalDatabaseFacadeExtensions</code>.</p>
<pre><code class="cs">public class TransactionsScenario : ITransactionsScenario&lt;EmployeeClassification&gt;
{
    private Func&lt;OrmCookbookContext&gt; CreateDbContext;

    public TransactionsScenario(Func&lt;OrmCookbookContext&gt; dBContextFactory)
    {
        CreateDbContext = dBContextFactory;
    }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        using (var context = CreateDbContext())
        using (var trans = context.Database.BeginTransaction())
        {
            context.EmployeeClassification.Add(classification);
            context.SaveChanges();
            var result = classification.EmployeeClassificationKey;

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        using (var trans = context.Database.BeginTransaction(isolationLevel))
        {
            context.EmployeeClassification.Add(classification);
            context.SaveChanges();
            var result = classification.EmployeeClassificationKey;

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public EmployeeClassification GetByKey(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
            return context.EmployeeClassification.Find(employeeClassificationKey);
    }
}
</code></pre>

<h2 id="entity-framework-core">Entity Framework Core<a class="headerlink" href="#entity-framework-core" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>EF Core will automatically create and commit a transaction when you call <code>SaveChanges()</code>. To override this behavior, you can explicitly create a transaction. </p>
<p>When setting the isolation level, you need to use an extension method defined in <code>Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions</code>.</p>
<pre><code class="cs">public class TransactionsScenario : ITransactionsScenario&lt;EmployeeClassification&gt;
{
    private Func&lt;OrmCookbookContext&gt; CreateDbContext;

    public TransactionsScenario(Func&lt;OrmCookbookContext&gt; dBContextFactory)
    {
        CreateDbContext = dBContextFactory;
    }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        using (var context = CreateDbContext())
        using (var trans = context.Database.BeginTransaction())
        {
            context.EmployeeClassifications.Add(classification);
            context.SaveChanges();
            var result = classification.EmployeeClassificationKey;

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var context = CreateDbContext())
        using (var trans = context.Database.BeginTransaction(isolationLevel))
        {
            context.EmployeeClassifications.Add(classification);
            context.SaveChanges();
            var result = classification.EmployeeClassificationKey;

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        using (var context = CreateDbContext())
            return context.EmployeeClassifications.Find(employeeClassificationKey);
    }
}
</code></pre>

<h2 id="linq-to-db">LINQ to DB<a class="headerlink" href="#linq-to-db" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>While the transaction is open, all operations are automatically associated with the transaction.</p>
<pre><code class="cs">public class TransactionsScenario : ITransactionsScenario&lt;EmployeeClassification&gt;
{
    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        using (var db = new OrmCookbook())
        using (var trans = db.BeginTransaction())
        {
            var result = db.InsertWithInt32Identity(classification);

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        using (var db = new OrmCookbook())
        using (var trans = db.BeginTransaction(isolationLevel))
        {
            var result = db.InsertWithInt32Identity(classification);

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        using (var db = new OrmCookbook())
        {
            return db.EmployeeClassification.Where(d =&gt; d.EmployeeClassificationKey == employeeClassificationKey).SingleOrDefault();
        }
    }
}
</code></pre>

<h2 id="llblgen-pro">LLBLGen Pro<a class="headerlink" href="#llblgen-pro" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>The <code>DataAccessAdapter</code> manages the transaction itself.</p>
<pre><code class="cs">public class TransactionsScenario : ITransactionsScenario&lt;EmployeeClassificationEntity&gt;
{
    public int Create(EmployeeClassificationEntity classification, bool shouldRollBack)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var adapter = new DataAccessAdapter())
        {
            adapter.StartTransaction(IsolationLevel.ReadCommitted, null);
            adapter.SaveEntity(classification, true, recurse: false);
            var result = classification.EmployeeClassificationKey;

            if (shouldRollBack)
{
    adapter.Rollback();
}
            else
{
    adapter.Commit();
}
            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassificationEntity classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var adapter = new DataAccessAdapter())
        {
            adapter.StartTransaction(isolationLevel, null);
            adapter.SaveEntity(classification, true, recurse: false);
            var result = classification.EmployeeClassificationKey;

            if (shouldRollBack)
{
    adapter.Rollback();
}
            else
{
    adapter.Commit();
}
            return result;
        }
    }

    public EmployeeClassificationEntity? GetByKey(int employeeClassificationKey)
    {
        using (var adapter = new DataAccessAdapter())
        {
            return new LinqMetaData(adapter).EmployeeClassification
                                .FirstOrDefault(ec =&gt; ec.EmployeeClassificationKey == employeeClassificationKey);
        }
    }
}
</code></pre>

<h2 id="nhibernate">NHibernate<a class="headerlink" href="#nhibernate" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>While the transaction is open, all operations are automatically associated with the transaction.</p>
<pre><code class="cs">public class TransactionsScenario : ITransactionsScenario&lt;EmployeeClassification&gt;
{
    readonly ISessionFactory m_SessionFactory;

    public TransactionsScenario(ISessionFactory sessionFactory)
    {
        m_SessionFactory = sessionFactory;
    }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var session = m_SessionFactory.OpenSession())
        using (var trans = session.BeginTransaction())
        {
            session.Save(classification);
            session.Flush();
            var result = classification.EmployeeClassificationKey;

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var session = m_SessionFactory.OpenSession())
        using (var trans = session.BeginTransaction(isolationLevel))
        {
            session.Save(classification);
            session.Flush();
            var result = classification.EmployeeClassificationKey;

            if (shouldRollBack)
                trans.Rollback();
            else
                trans.Commit();

            return result;
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        using (var session = m_SessionFactory.OpenStatelessSession())
            return session.Get&lt;EmployeeClassification&gt;(employeeClassificationKey);
    }
}
</code></pre>

<h2 id="repodb">RepoDb<a class="headerlink" href="#repodb" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<p>Simply call the <code>BeginTransaction()</code> method of the <code>DbConnection</code> object and pass the instance of <code>DbTransaction</code> when you are calling any of the operations.</p>
<pre><code class="cs">public class TransactionsScenario : BaseRepository&lt;EmployeeClassification, SqlConnection&gt;,
    ITransactionsScenario&lt;EmployeeClassification&gt;
{
    public TransactionsScenario(string connectionString)
        : base(connectionString, RDB.Enumerations.ConnectionPersistency.Instance)
    { }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var transaction = CreateConnection().EnsureOpen().BeginTransaction())
        {
            var result = Insert&lt;int&gt;(classification, transaction: transaction);

            if (shouldRollBack)
                transaction.Rollback();
            else
                transaction.Commit();

            return result;
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var transaction = CreateConnection().EnsureOpen().BeginTransaction(isolationLevel))
        {
            var result = Insert&lt;int&gt;(classification, transaction: transaction);

            if (shouldRollBack)
                transaction.Rollback();
            else
                transaction.Commit();

            return result;
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        return Query(e =&gt; e.EmployeeClassificationKey == employeeClassificationKey).FirstOrDefault();
    }
}
</code></pre>

<h2 id="servicestack">ServiceStack<a class="headerlink" href="#servicestack" title="Permalink to this headline"><i class="fa fa-link" aria-hidden="true"></i></a></h2>
<pre><code class="cs">internal class TransactionsScenario : ITransactionsScenario&lt;EmployeeClassification&gt;
{
    private IDbConnectionFactory _dbConnectionFactory;

    public TransactionsScenario(IDbConnectionFactory dbConnectionFactory)
    {
        this._dbConnectionFactory = dbConnectionFactory;
    }

    public int Create(EmployeeClassification classification, bool shouldRollBack)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            using(var tx = db.OpenTransaction())
            {
                var result = (int) db.Insert(classification, true);

                if (shouldRollBack)
                    tx.Rollback();
                else
                    tx.Commit();

                return result;
            }
        }
    }

    public int CreateWithIsolationLevel(EmployeeClassification classification, bool shouldRollBack, IsolationLevel isolationLevel)
    {
        if (classification == null)
            throw new ArgumentNullException(nameof(classification), $&quot;{nameof(classification)} is null.&quot;);

        using (var db = _dbConnectionFactory.OpenDbConnection())
        {
            using(var tx = db.OpenTransaction(isolationLevel))
            {
                var result = (int) db.Insert(classification, true);

                if (shouldRollBack)
                    tx.Rollback();
                else
                    tx.Commit();

                return result;
            }
        }
    }

    public EmployeeClassification? GetByKey(int employeeClassificationKey)
    {
        using (var db = _dbConnectionFactory.OpenDbConnection())
            return db.SingleById&lt;EmployeeClassification&gt;(employeeClassificationKey);
    }
}
</code></pre>


                    </div>
                </div>
                <footer>
                    <hr />
                    <div role="contentinfo">
The ORM Cookbook. <a href='https://github.com/Grauenwolf/DotNet-ORM-Cookbook' target='_blank'>Visit us at GitHub</a>.
                    </div>
                </footer>
            </div>
        </section>
    </div>
    <script src="js/jquery-2.1.1.min.js"></script>
    <script src="js/modernizr-2.8.3.min.js"></script>
    <script src="js/highlight.pack.js"></script>
    <script src="js/theme.js"></script>

</body>
</html>
